<template>
  <div>
    <el-dialog
      :title="mode === 'add' ? '添加角色' : '编辑角色'"
      :visible="isShow"
      width="500px"
      @close="closeEvent"
    >
      <el-form label-width="100px" :model="form" :rules="rules" ref="form">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model.trim="form.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="closeEvent">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setting'
export default {
  name: 'dialogItem',
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  model: { prop: 'isShow' },
  data () {
    return {
      mode: 'add',
      infoForm:'',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let result = ''
              if (this.mode === 'add') {
                //不能与当前项重名
                result = this.list.some(item => {
                  return item.name === value
                })
              } else {
                //编辑，排除当前点击项
                result = this.list.some(item => {
                  return item.name === value && item.id !== this.form.id
                })
              }
              result ? callback(new Error('请不要重名')) : callback()
            }
          }
        ],
        description: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  created(){
// this.infoForm=JSON.parse(JSON.stringify(this.form))
  },
  methods: {
    closeEvent () {
      this.$emit('update:isShow', false)
      //重置表单数据
      this.$refs.form.resetFields()
      //表单数据还原
      this.form = {
        name: '',
        description: ''
      }
    //   this.form=JSON.parse(JSON.stringify(this.infoForm))
    },
    //提交
    submit () {
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            await sysRolePost(this.form)
            //刷新父级列表数据
            this.$emit('CurrentChange', 1)
          } else {
            await sysRolePut(this.form)
          }
          //提示
          this.$message.success('添加成功')
          //关闭弹窗
          this.closeEvent()
          this.$emit('getDate')
          console.log(result)
        }
      })
    }
  }
}
</script>

<style></style>
